//app.js
const api = require('api.js');
var o = require("utils/jquery.js");
App({
  onLaunch: function() {
    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)


    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.userInfo = res.userInfo

              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })
  },


  globalData: {
    userInfo: null,
    rdsession: '',
    acct_id: 1,
    openid: "",
    localSocket: {},
  },
  login: function() {
    is_login = true;
    wx.checkSession({
      success: function() {
        var access_token = wx.getStorageSync('access_token');
        if (!access_token) {
          getApp().login_1();
        } else {
          is_login = false;
        }
      },
      fail: function() {
        getApp().login_1();
      }
    });
  },
  login_1: function() {
    if (is_login) {
      return;
    }
    is_login = true;
    var pages = getCurrentPages();
    var page = pages[(pages.length - 1)];
    wx.login({
      success: function(res) {
        if (res.code) {
          var code = res.code;
          console.log(code)

          wx.getUserInfo({
            success: function(res) {
              console.log(res);
              getApp().request({
                url: api.user.login,
                method: "POST",
                data: {
                  code: code,
                  user_info: res.rawData,
                  encrypted_data: res.encryptedData,
                  iv: res.iv,
                  signature: res.signature
                },
                success: function(result) {
                  console.log('===>1212')
                  wx.hideLoading();
                  is_login = false;
                  if (result.code == 0) {
                    wx.setStorageSync("rdsession", result.data.rdsession);
                    wx.setStorageSync("openid", result.data.openid);
                    wx.setStorageSync("user_info", {
                      nickname: result.data.nickname,
                      avatar_url: result.data.avatar_url,
                      id: result.data.id,
                      is_comment: result.data.is_comment
                    });
                    var pages_now = getCurrentPages();
                    var page_now = pages_now[(pages_now.length - 1)];
                    page_now.onShow();
                    page_now.onLoad(pages_now.options);
                    if (page == undefined) {
                      return;
                    }
                  } else {
                    wx.showModal({
                      title: '警告',
                      content: result.errmsg,
                      showCancel: false
                    })
                  }
                }
              });
            },
            fail: function(e) {
              wx.hideToast();
              getApp().getauth({
                content: '需要获取您的用户信息授权',
                cancel: true,
                success: function(e) {
                  if (e) {
                    getApp().login_1();
                  }
                },
              });
            }
          });
        } else {
          wx.showToast({
            title: res.msg
          });
        }
      },
      fail: function(e) {
        console.log(e);
      }
    });
  },
  str2Obj: function(t) {
    if ("string" != typeof t) return t;
    if (t.indexOf("&") < 0 && t.indexOf("=") < 0) return {};
    var e = t.split("&"),
      n = {};
    return o.each(e, function(t, e) {
      if (e.indexOf("=") > -1) {
        var o = e.split("=");
        n[o[0]] = o[1];
      }
    }), n;
  },
  getauth: function(object) {
    wx.navigateTo({
      url: '/pages/usersq/usersq',
    })
  },
  request: function(object) {
    var rdsession = wx.getStorageSync("rdsession");
    var openid = wx.getStorageSync("openid");
    var unionid = wx.getStorageSync("unionid");
    if (!object.data) {
      object.data = {};
    }
    wx.request({
      url: object.url,
      header: object.header || {
        'content-type': 'application/x-www-form-urlencoded',
        'rdsession': rdsession,
        'openid': openid,
        'unionid': unionid,
        'acctid': this.globalData.acct_id,
        'version': "2.0"
      },
      data: object.data || {},
      method: object.method || "GET",
      dataType: object.dataType || "json",
      success: function(res) {
        if (res.data.errcode == 1003) {

          console.log('==>-1')
          wx.navigateTo({
            url: '/pages/usersq/usersq',
          })
          return false;
        } else if (res.data.errcode == 1006){
          wx.navigateTo({
            url: '/pages/userss/userss',
          })
          return false;
        } else {
          if (object.success)
            object.success(res.data);
        }
      },
      fail: function(res) {
        var app = getApp();
        if (app.is_on_launch) {
          app.is_on_launch = false;
          wx.showModal({
            title: "网络请求出错",
            content: res.errMsg,
            showCancel: false,
            success: function(res) {
              if (res.confirm) {
                if (object.fail)
                  object.fail(res);
              }
            }
          });
        } else {
          wx.showToast({
            title: res.errMsg,
            image: "/images/icon-warning.png",
          });
          if (object.fail)
            object.fail(res);
        }
      },
      complete: function(res) {
        if (object.complete)
          object.complete(res);
      }
    });
  },
  upload: function(t) {
    var e = this;
    wx.chooseImage({
      success: function(n) {
        wx.showLoading({
          title: '正在上传...',
        });
        var i = n.tempFilePaths;
        wx.uploadFile({
          url: api.default.upload_img,
          filePath: i[0],
          name: "image",
          success: function(n) {
            wx.hideLoading();
            var o = JSON.parse(n.data);
            if (0 != o.errcode){
              wx.showToast({
                title: '上传失败',
                icon: 'none'
              });
            } 
            else if ("function" == typeof t) {
              var i = o.data;
              t(i);
            }
          }
        });
      }
    });
  },
 


})